package com.fc.push.handler.pub.service;

import java.util.Date;
import java.util.Set;

import com.fc.persistence.cache.ConstKey;
import com.fc.push.GlobalServerConst;

import redis.clients.jedis.Jedis;

public class RedisService {
	// token保存30天，30天之后要重新注册
	public static final long ONE_MONTH_IN_MILLISECONDS = 30 * 24 * 60 * 60 * 1000;

	/**
	 * 判断是否要清除token
	 * 
	 * @param appkey
	 * @param token
	 * @return
	 */
	public static boolean isCleanToken(Jedis jedis, String appkey, String token) {
		long cutoff = new Date().getTime() - ONE_MONTH_IN_MILLISECONDS;
		double score = jedis.zscore(appkey, token);
		// double score = SharedJedisFacade.zscoreProxy(appkey, token);
		if (score < cutoff) {
			return true;
		}
		return false;
	}

	/**
	 * 保存应用下的token，和注册时间
	 * 
	 * @param appkey
	 * @param token
	 * @return
	 */
	public static boolean addTokenWithTimeStamp(Jedis jedis, String appkey, String token) {
		jedis.zadd(appkey, new Date().getTime(), token);
		// SharedJedisFacade.zaddProxy(appkey, new Date().getTime(), token);
		return true;
	}

	/**
	 * 删除应用tag下的token
	 * 
	 * @param appkey
	 * @param platform
	 * @param token
	 * @return
	 */
	public static boolean removeTokenInTag(Jedis jedis, String appkey, String platform, String token) {
		if (jedis.zscore(appkey, token) == null) {
			return true;
		}
		jedis.zrem(appkey, token);

		String tagKey = "";
		String key = "";
		switch (platform.toLowerCase()) {
		case GlobalServerConst.ANDROID:
			tagKey = ConstKey.AN_APP_SET_TAG;
			key = ConstKey.AN_APP_TAG_SET_IDS;
			break;
		case GlobalServerConst.IOS:
			tagKey = ConstKey.IOS_APP_SET_TAG;
			key = ConstKey.IOS_APP_TAG_SET_TOKENS;
			break;
		case GlobalServerConst.H5:
			break;
		case GlobalServerConst.WEB:
			tagKey = ConstKey.WEB_APP_SET_TAG;
			key = ConstKey.WEB_APP_TAG_SET_IDS;
			break;
		}
		tagKey = tagKey.replaceFirst("APP", appkey);
		Set<String> tags = jedis.smembers(tagKey);
		for (String tag : tags) {
			key = key.replaceFirst("APP", appkey);
			key = key.replaceFirst("TAG", tag);
			jedis.srem(key, token);
		}
		return true;
	}
}